import threading
from typing import Optional
from loguru import logger
from .camera_interface import CameraInterface
import cv2


class CameraBase(CameraInterface):
    def __init__(self):
        super().__init__()
        self._cap: Optional[cv2.VideoCapture] = None
        logger.info('CameraBase已创建')
        self._size = None
        self.current_frame_id = 0
        self.current_frame = None

    def open_camera(self):
        logger.info('打开相机')
        self._cap = cv2.VideoCapture(2)

        if self._cap.isOpened():
            logger.info('相机打开成功')
            self._cap.set(3, 1920)
            self._cap.set(4, 1080)

            self._size = (int(self._cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(self._cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
            logger.info(f'camera size:{self._size}')
        else:
            logger.error('相机打开失败')

    def close_camera(self):
        super().close_camera()
        if self._cap is not None:
            logger.info('关闭相机')
            self._cap.release()

    def get_frame(self):
        if not self._cap.isOpened():
            logger.warning('相机未打开')
            return
        ret, frame = self._cap.read()
        if not ret:
            logger.warning('未获取到帧')
            return
        self.close_camera()
        cv2.imshow('image', cv2.resize(frame, (1280, 720)))
        cv2.waitKey(0)

    def record(self):
        t = threading.Thread(target=self._record_thread)
        t.daemon = True
        t.start()

    def _record_thread(self):
        logger.info('开始录像')
        self.current_frame_id = 0
        self.current_frame = None
        if not self._cap.isOpened():
            logger.warning('相机未打开')
            return
        while True:
            logger.info(f'kill_record_thread:{self.kill_record_thread}')
            if self.kill_record_thread:
                break
            ret, frame = self._cap.read()
            if ret:
                self.current_frame = frame
                self.current_frame_id += 1
                cv2.imshow('image', cv2.resize(frame, (1280, 720)))
                cv2.waitKey(1)
        self.close_camera()


if __name__ == '__main__':
    logger.add('run.log')
    cam = CameraBase()
    cam.open_camera()
    cam.record()
    input()
    cam.stop_record()
    input()

